// 按钮类型定义
export type MessageBoxButton =
  | 'ok'
  | 'yes-no'
  | 'ok-cancel'
  | 'abort-retry-ignore'
  | 'yes-no-cancel'

// 按钮文本映射
export const buttonTextMap: Record<MessageBoxButton, string[]> = {
  ok: ['确定'],
  'yes-no': ['是', '否'],
  'ok-cancel': ['确认', '取消'],
  'abort-retry-ignore': ['中止', '重试', '忽略'],
  'yes-no-cancel': ['是', '否', '取消'],
}

// 返回值映射
export type MessageBoxResult = 'ok' | 'yes' | 'no' | 'cancel' | 'abort' | 'retry' | 'ignore'

// MessageBox 参数定义
export interface MessageBoxOptions {
  message: string
  icon: 'success' | 'error' | 'warning' | 'info' | 'none'
  button: MessageBoxButton
  title?: string
  defaultButton?: number // 0-based index
}

// Toast 参数定义
export interface ToastOptions {
  message: string
  type: 'success' | 'error' | 'warning' | 'info'
  duration?: number
  id?: number
}

// 内部队列项
interface MessageBoxQueueItem {
  options: MessageBoxOptions
  resolve: (result: MessageBoxResult) => void
}

export const useUIStore = defineStore('ui', () => {
  // ====== Toast 状态 ======
  const toasts = ref<ToastOptions[]>([])
  let toastIdCounter = 0

  const showToast = (options: ToastOptions) => {
    const id = ++toastIdCounter
    const toast = {
      ...options,
      id,
      duration: options.duration || 6000,
    }

    toasts.value.push(toast)

    setTimeout(() => {
      removeToast(id)
    }, toast.duration)
  }

  const removeToast = (id: number) => {
    const index = toasts.value.findIndex((toast) => toast.id === id)
    if (index !== -1) {
      toasts.value.splice(index, 1)
    }
  }

  // ====== MessageBox 状态 ======
  const messageBoxQueue = ref<MessageBoxQueueItem[]>([])
  const currentMessageBox = ref<MessageBoxQueueItem | null>(null)

  // 显示 MessageBox（供内部队列使用）
  const showNextMessageBox = () => {
    if (messageBoxQueue.value.length === 0) {
      currentMessageBox.value = null
      return
    }
    const item = messageBoxQueue.value.shift()
    if (!item) {
      currentMessageBox.value = null
      return
    }
    currentMessageBox.value = item
  }

  // 外部调用 API：返回 Promise
  const showMessageBox = (
    message: string,
    icon: MessageBoxOptions['icon'],
    button: MessageBoxButton,
    title?: string,
    defaultButton?: number,
  ): Promise<MessageBoxResult> => {
    return new Promise((resolve) => {
      const item: MessageBoxQueueItem = {
        options: { message, icon, button, title, defaultButton },
        resolve,
      }
      messageBoxQueue.value.push(item)
      // 如果当前没有正在显示的 MessageBox，立即显示
      if (!currentMessageBox.value) {
        showNextMessageBox()
      }
    })
  }

  // 用户点击按钮时调用
  const handleMessageBoxResult = (result: MessageBoxResult) => {
    if (!currentMessageBox.value) return
    currentMessageBox.value.resolve(result)
    showNextMessageBox()
  }

  // 点击遮罩或关闭按钮时的默认行为
  const handleMessageBoxClose = () => {
    if (!currentMessageBox.value) return

    const { button } = currentMessageBox.value.options

    // 根据按钮类型决定默认行为
    if (button === 'ok') {
      handleMessageBoxResult('ok')
    } else if (button === 'yes-no') {
      // 不允许关闭
      return
    } else if (button === 'ok-cancel' || button === 'yes-no-cancel') {
      handleMessageBoxResult('cancel')
    } else if (button === 'abort-retry-ignore') {
      // 不允许关闭
      return
    }
  }

  return {
    // Toast
    toasts,
    showToast,
    removeToast,

    // MessageBox
    messageBoxQueue,
    currentMessageBox,
    showMessageBox,
    handleMessageBoxResult,
    handleMessageBoxClose,
  }
})
